package com.quyunshuo.module.home.view

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.core.content.withStyledAttributes
import com.quyunshuo.module.home.R

@SuppressLint("Recycle", "DrawAllocation")
class CircleProgressView2 @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 背景圆的画笔
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
    }

    // 进度弧线的画笔
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND // 进度条两端为圆角
    }

    // 绘制区域矩形
    private val oval = RectF()

    // 当前进度 (0-100)
    private var progress = 0f
        set(value) {
            field = value.coerceIn(0f, 100f)
            invalidate()
        }

    // 进度条宽度
    private var strokeWidth = 15f

    // 进度条起始角度（从12点方向开始）
    private val startAngle = -90f

    // 动画持续时间
    private val animationDuration = 1000L

    // 默认颜色值
    private var defaultBackgroundColor = Color.LTGRAY
    private var defaultProgressColor = Color.BLUE

    init {
        // 初始化默认值
        backgroundPaint.color = defaultBackgroundColor
        backgroundPaint.strokeWidth = strokeWidth
        
        progressPaint.color = defaultProgressColor
        progressPaint.strokeWidth = strokeWidth
        
        // 从XML属性中获取自定义值
        context.withStyledAttributes(attrs, R.styleable.CircleProgressView) {
            backgroundPaint.color = getColor(
                R.styleable.CircleProgressView_backgroundColor,
                defaultBackgroundColor
            )
            
            progressPaint.color = getColor(
                R.styleable.CircleProgressView_progressColor,
                defaultProgressColor
            )
            
            strokeWidth = getDimension(
                R.styleable.CircleProgressView_strokeWidth,
                strokeWidth
            )
            
            backgroundPaint.strokeWidth = strokeWidth
            progressPaint.strokeWidth = strokeWidth
            
            progress = getFloat(R.styleable.CircleProgressView_progress, 0f)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        
        // 确保视图为正方形（取宽高中较小者）
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        val size = width.coerceAtMost(height)
        setMeasuredDimension(size, size)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        
        // 计算绘制区域，留出边框空间
        val padding = strokeWidth / 2
        oval.set(
            padding,
            padding,
            w - padding,
            h - padding
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        // 1. 绘制背景圆
        canvas.drawOval(oval, backgroundPaint)
        
        // 2. 绘制进度弧线（从12点位置开始，顺时针方向）
        val sweepAngle = (progress / 100f) * 360f
        canvas.drawArc(oval, startAngle, sweepAngle, false, progressPaint)
        
        // 3. 中心点绘制（测试用，可选）
        // val centerX = width / 2f
        // val centerY = height / 2f
        // canvas.drawCircle(centerX, centerY, 5f, progressPaint)
    }

    /**
     * 设置进度
     * @param newProgress 0-100之间的值
     * @param animate 是否使用动画过渡
     */
    fun setProgress(newProgress: Float, animate: Boolean = true) {
        val targetProgress = newProgress.coerceIn(0f, 100f)
        
        if (animate) {
            ValueAnimator.ofFloat(progress, targetProgress).apply {
                duration = animationDuration
                interpolator = DecelerateInterpolator()
                addUpdateListener { animator ->
                    progress = animator.animatedValue as Float
                }
                start()
            }
        } else {
            progress = targetProgress
        }
    }

    /**
     * 设置背景圆颜色
     */
    fun setBackgroundColor2(color: Int) {
        backgroundPaint.color = color
        invalidate()
    }

    /**
     * 设置进度条颜色
     */
    fun setProgressColor(color: Int) {
        progressPaint.color = color
        invalidate()
    }

    /**
     * 设置进度条宽度
     */
    fun setStrokeWidth(width: Float) {
        strokeWidth = width
        backgroundPaint.strokeWidth = strokeWidth
        progressPaint.strokeWidth = strokeWidth
        requestLayout() // 需要重新计算布局
    }
}